<template>
    <div>
        <ul ref="ul" class="meul">

        </ul>
        <div id="editor" ref="input"></div>
        <el-button type="primary" @click="add1">发布消息</el-button>
    </div>
</template>

<script>
    import E from 'wangeditor'
    import {getCurrentInstance, reactive, toRefs, onMounted} from 'vue'
    import api from "../../api";
    import {ElMessage} from 'element-plus'
    export default {
        name: "Message",
        setup() {
            let data=reactive({
                editor:'',
                html:'',
                li:''
            })
            onMounted(() => {
                let $this = getCurrentInstance()
                // 获取wang编辑实例
                data.editor = new E('#editor')
                data.editor.config.onchange=html=>{
                    // 获取wang编辑文本框内容
                    data.html=data.editor.txt.html()
                }
                // 创建wang编辑
                data.editor.create()
                let ul = $this.refs.ul
                data.li = document.createElement('li');
                ul.appendChild(data.li)
                getMessageList()
            })
            // 获取消息列表
            let getMessageList=()=>{
                api.getMessage().then(res=>{
                    let arr= res.data.data.map(r=>{
                        return r.sendM
                    })
                    if (res.data.status===200){
                        data.li.innerHTML=arr
                    }else {
                        ElMessage.error('获取信息失败')
                    }

                })
            }
            let $this = getCurrentInstance()
            let add1 = () => {
                // 获取ul dom元素
            api.getMessageAdd({message:data.html}).then(res=>{
                if (res.data.status===200){
                    let ul = $this.refs.ul
                    let li = document.createElement('li');
                    li.innerHTML =data.html
                    ul.appendChild(li)
                    ElMessage.success('发布成功')
                    // 清空编辑器
                    data.editor.txt.clear()
                }else {
                    ElMessage.error('发布失败')
                }
             })
            }
            return {
                add1,
            ...toRefs(data)
            }
        },


    }
</script>

<style scoped>
    li{
        color: orange;
    }
    #editor {
        margin-top: 260px;
    }
    .el-button{
        margin-top: 10px;
    }
</style>
